package cn.hdu.liang.concurrency;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

class SleepBlocked implements Runnable {
    @Override
    public void run() {
        try {
            TimeUnit.SECONDS.sleep(100);
        } catch(InterruptedException e) {
            System.out.println("中断异常");
        }
        System.out.println("退出SleepBlocked.run()");
    }
}

class IOBlocked implements Runnable {
    private InputStream in;

    public IOBlocked(InputStream is) {
        in = is;
    }

    @Override
    public void run() {
        try {
            System.out.println("等待读");
            in.read();
        } catch(IOException e) {
            if(Thread.currentThread().isInterrupted()) {
                System.out.println("从阻塞IO中中断");
            } else {
                throw new RuntimeException(e);
            }
        }
        System.out.println("退出IOBlocked.run()");
    }
}


class SynchronizedBlocked implements Runnable {
    public synchronized void f() {
        while(true) {
            Thread.yield();
        }
    }

    public SynchronizedBlocked() {
        new Thread() {
            @Override
            public void run() {
                f();
            }
        }.start();
    }

    @Override
    public void run() {
        System.out.println("尝试调用f()");
        f();
        System.out.println("退出SynchronizedBlocked.run()");
    }
}

public class Interrupting {
    private static ExecutorService exec = Executors.newCachedThreadPool();

    static void test(Runnable r) throws InterruptedException {
        Future<?> f = exec.submit(r);
        TimeUnit.MILLISECONDS.sleep(100);
        System.out.println("打断 " + r.getClass().getName());
        f.cancel(true);
        System.out.println("中断 发送 " + r.getClass().getName());
    }

    public static void main(String[] args) throws InterruptedException {
        test(new SleepBlocked());
        System.out.println();
        test(new IOBlocked(System.in));
        System.out.println();
        test(new SynchronizedBlocked());
        System.out.println();
        TimeUnit.SECONDS.sleep(3);
        System.out.println("System.exit(0) 中断");
        System.exit(0);
    }
}
